package com.bestcem.xm.survey.grpc.client;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.openplatform.grpc.v1.services.*;
import com.bestcem.xm.survey.convert.grpc.SurveyGrpcConvertMapper;
import com.bestcem.xm.survey.grpc.client.dto.ExtParamDto;
import com.bestcem.xm.survey.grpc.client.dto.ExtParamEnumManageDto;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Component
public class OpenPlatformGrpcClient {

    @GrpcClient(GrpcClientNames.DS_OPENPLATFORM)
    private BaseOpenplatformServiceGrpc.BaseOpenplatformServiceBlockingStub stub;

    private final SurveyGrpcConvertMapper grpcConvertMapper;

    public OpenPlatformGrpcClient(SurveyGrpcConvertMapper grpcConvertMapper) {
        this.grpcConvertMapper = grpcConvertMapper;
    }

    public List<ExtParamEnumManageDto> listExtParamEnumManage(JSONObject params) {
        ListExtParamEnumManageRequest.Builder builder = ListExtParamEnumManageRequest.newBuilder();
        builder.setSearch(Optional.ofNullable(params.getString("search")).orElse(""));
        params.remove("search");

        String statusStr = params.getString("status");
        if (StrUtil.isNotEmpty(statusStr) && JSONUtil.isTypeJSONArray(statusStr)) {
            builder.addAllStatus(JSONArray.parseArray(statusStr).toJavaList(Integer.class));
            params.remove("status");
        } else {
            builder.addAllStatus(Lists.newArrayList());
        }

        ExtParamEnumManageDto requestDto = JSONObject.toJavaObject(params, ExtParamEnumManageDto.class);
        builder.setExtParamEnumManage(grpcConvertMapper.toGrpcExtParamEnumManage(requestDto));

//        builder.addAllFields(null);
        try {
            ExtParamEnumManageSearchResponse response = stub.listExtParamEnumManage(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] listExtParamEnumManage Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toExtParamEnumManageDtoList(response.getExtParamEnumManageListList());
        } catch (Exception e) {
            log.error("[survey] ex listExtParamEnumManage Error, ErrorMsg:", e);
            return null;
        }
    }

    public List<ExtParamDto> listExtParam(JSONObject params) {
        JSONObject query = new JSONObject();
        query.putAll(params);
        ListExtParamRequest.Builder builder = ListExtParamRequest.newBuilder();

        builder.setSearch(Optional.ofNullable(query.getString("search")).orElse(""));
        query.remove("search");

        String statusStr = query.getString("status");
        if (StrUtil.isNotEmpty(statusStr) && JSONUtil.isTypeJSONArray(statusStr)) {
            builder.addAllStatus(JSONArray.parseArray(statusStr).toJavaList(Integer.class));
            query.remove("status");
        } else {
            builder.addAllStatus(Lists.newArrayList());
        }

        ExtParamDto requestDto = JSONObject.toJavaObject(query, ExtParamDto.class);
        builder.setExtParam(grpcConvertMapper.toGrpcExtParam(requestDto));

//        builder.addAllFields(null);
        try {
            ExtParamSearchResponse response = stub.listExtParam(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] listExtParam Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toExtParamDtoList(response.getExtParamListList());
        } catch (Exception e) {
            log.error("[survey] ex listExtParam Error, ErrorMsg:", e);
            return null;
        }
    }

    public List<EncryptionConfig> listEncryptionConfig(JSONObject params) {
        ListEncryptionConfigRequest.Builder builder = ListEncryptionConfigRequest.newBuilder();

        EncryptionConfig.Builder encryptionConfigBuilder = EncryptionConfig.newBuilder();
        encryptionConfigBuilder.setOrgId(params.getString("org_id"));

        builder.setEncryptionConfig(encryptionConfigBuilder);
        builder.setSearch(Optional.ofNullable(params.getString("search")).orElse(""));
        builder.addAllStatus(Lists.newArrayList());
//        builder.addAllFields(null);
        try {
            EncryptionConfigSearchResponse response = stub.listEncryptionConfig(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] listEncryptionConfig, params = {} Error; ErrorMsg: {}", params.toJSONString(), response);
                return null;
            }
            return response.getEncryptionConfigListList();
        } catch (Exception e) {
            log.error("[survey] ex listEncryptionConfig, params = {}  Error; ErrorMsg: {}", params.toJSONString(), e);
            return null;
        }
    }
}
